var findlmdata_link = webrootpath+"lm/findlmdata";
var insertlm_link = webrootpath+"lm/insertlm";
var adddocframe_link = "./docedit.html";
var getdoclistbylmidlink = webrootpath+"doc/getdoclistbylmidlink";
var deletedocbydocid = webrootpath+"doc/deletedocbydocid";
var deletelmbylmid = webrootpath+"lm/deletelmbylmid";
var i_w_importdoc_importlink = webrootpath+"doc/i_w_importdoc_importlink";
var upload_file = webrootpath+"file/upload_file"; //上传文件
var delAttached_link = webrootpath+"doc/delAttached_link"; //删除附件
var qingkong_doclink = webrootpath+"doc/qingkong_doclink"; //清空该分类下所有文档
var save_glkplink = webrootpath+"doc/save_glkplink"; //生成该分类下的概要卡片
var yincang_zhaiyaolink = webrootpath+"doc/yincang_zhaiyaolink"; //生成该分类下的概要卡片2
var publicDoclink = webrootpath+"doc/publicDoclink";//文档发布
var model_indexlm_addbianliang_submitlink = webrootpath+"lm/model_indexlm_addbianliang_submitlink";//添加栏目属性变量
var model_indexlm_selectbianlianglink = webrootpath+"lm/model_indexlm_selectbianlianglink";//查询文档概要属性信息
var delete_lm_bianlianglink = webrootpath+"lm/delete_lm_bianlianglink";//根据id删除变量
var index_lm_createlmtemplatelink = webrootpath+"lm/index_lm_createlmtemplatelink";//生成栏目文档模板
var boollmdocauthlink = webrootpath+"lm/boollmdocauthlink";//栏目文档操作权限验证
var doc_pages = 1;
var docview_link = "./docview.html";
$(function () {
    findlmdata_link_fun(-1);
    index_lm_tab(1);
});



/***
 * 栏目导航
 * @param _index
 */
function index_lm_tab(_index) {
    $("#index_lm_ul li").removeClass("active");
    $("#index_lm_cont_0").hide();
    $("#index_lm_cont_1").hide();
    $("#index_lm_cont_2").hide();
    if(_index=="0"){
        $("#index_lm_ul li:eq(0)").addClass("active");
        $("#index_lm_cont_0").show();
        model_indexlm_selectbianliang();
    }else if (_index=="1"){
        $("#index_lm_ul li:eq(1)").addClass("active");
        $("#index_lm_cont_1").show();
    }else if(_index=="2"){
        $("#index_lm_ul li:eq(2)").addClass("active");
        $("#index_lm_cont_2").show();
    }
}

/****
 * 生成栏目文档模板
 */
function index_lm_createlmtemplate() {
    var treeObj = $.fn.zTree.getZTreeObj("index_lm_tree");
    var nodes = treeObj.getSelectedNodes();
    var selectcateid =  nodes[0].cateid;
    $.get(index_lm_createlmtemplatelink,{
        selectcateid:selectcateid
    },function (_info) {
        if(_info.code=="1"){
            window.open(_info.httppath);
        }else {
            alert("模板生成失败");
        }
    });
}
/***
 * 根据id删除该变量
 * @param _propertiesid
 */
function delete_lm_bianliang(_propertiesid) {
    var r = confirm("您确定要删除此变量吗？");
    if(r){
        $.get(delete_lm_bianlianglink,{
            propertiesid:_propertiesid
        },function (_info) {
            if(_info.code=="1"){
                $.alert(_info.msg);
                model_indexlm_selectbianliang();
            }
        });
    }
}
/**
 * 查询当前栏目下的数据
 */
function model_indexlm_selectbianliang() {
    var treeObj = $.fn.zTree.getZTreeObj("index_lm_tree");
    var nodes = treeObj.getSelectedNodes();
    var selectcateid =  nodes[0].cateid;
    $.get(model_indexlm_selectbianlianglink,{
        selectcateid:selectcateid
    },function (_info) {
        if(_info.code=="1"){
            var datalist = _info.data;
            var htmlstr = "";
            for(var i in datalist){
                var dataobj = datalist[i];
                htmlstr +="<tr>" +
                    "<td><input type='checkbox' />"+(parseInt(i)+1)+"</td>" +
                    "<td>"+dataobj.propertiesname+"</td>" +
                    "<td>"+dataobj.propertiescontent+"</td>" +
                    "<td>"+dataobj.propertiesdesc+"</td>" +
                    "<td>" +
                    "<button type=\"button\" style='margin-left: 10px;' class=\"btn btn-info\"     onclick='update_lm_bianliang(\""+dataobj.propertiesid+"\")'>修改</button>" +
                    "<button type=\"button\" style='margin-left: 10px;' class=\"btn btn-danger\" onclick='delete_lm_bianliang(\""+dataobj.propertiesid+"\")'>删除</button>" +
                    "</td>" +
                    "</tr>";
            }
            $("#index_lm_cont_0_content").html(htmlstr);

        }
    });
}
/***
 * 添加概要模板变量
 */
function model_indexlm_addbianliang_submit() {
    var treeObj = $.fn.zTree.getZTreeObj("index_lm_tree");
    var nodes = treeObj.getSelectedNodes();
    var selectcateid =  nodes[0].cateid;

    var model_indexlm_addbianliang_name = $.trim($("#model_indexlm_addbianliang_name").val());
    var model_indexlm_addbianliang_content = $.trim($("#model_indexlm_addbianliang_content").val());
    var model_indexlm_addbianliang_desc = $.trim($("#model_indexlm_addbianliang_desc").val());
    if(model_indexlm_addbianliang_name==""){
        $.alert("名称不能为空");
        return false;
    }
    $.post(model_indexlm_addbianliang_submitlink,{
        selectcateid:selectcateid,
        model_indexlm_addbianliang_name:model_indexlm_addbianliang_name,
        model_indexlm_addbianliang_content:model_indexlm_addbianliang_content,
        model_indexlm_addbianliang_desc:model_indexlm_addbianliang_desc
    },function (_info) {
        $("#model_indexlm_addbianliang").modal("hide");
        if(_info.code=="1"){
            $.alert(_info.msg);
            model_indexlm_selectbianliang();
        }
    });


}

/***
 * 添加概要模板变量(模态框)
 */
function index_lm_addbianliang() {
    $("#model_indexlm_addbianliang_name").val("");
    $("#model_indexlm_addbianliang_desc").val("");
    $("#model_indexlm_addbianliang").modal("show");
}


/***
 * 生成概要卡片
 */
function save_glkp() {
    var treeObj = $.fn.zTree.getZTreeObj("index_lm_tree");
    var nodes = treeObj.getSelectedNodes();
    var selectcateid =  nodes[0].cateid;

    var r=confirm("您确定生成当前分类下的概要卡片吗？");
    if (r==true){
        $.get(save_glkplink,{selectcateid:selectcateid},function (msg) {
            if(msg.code=='1'){
                var msgdata = msg.data;
                var msgdatalength = msgdata.length;
                save_glkp_content(msgdata,msgdatalength,0);
            }
        });
    }

}
function save_glkp_content(msgdata,msgdatalength,_num) {
    if(_num<msgdatalength){
        $("#yincang_zhaiyao").load("./doc_template/doc_gaiyao.html",function(){
            var msgdataobj =  msgdata[_num];
            $("#zhaiyaobody_docname").html(msgdataobj.data.doctitle);
            $("#zhaiyaobody_doccontent").html(msgdataobj.data.doccontent);
            $("#zhaiyaobody_docimage").attr("src",(msgdataobj.attached.fangwenuepath+msgdataobj.attached.attacheddata));
            setTimeout(function () {
                var yincang_zhaiyao_html = $("#yincang_zhaiyao").html();
                $.post(yincang_zhaiyaolink,{yincang_zhaiyao_html:yincang_zhaiyao_html},function (_info) {
                    if(_info.code=="1"){
                        console.log("生成完毕"+_num);

                        _num = _num+1;
                        save_glkp_content(msgdata,msgdatalength,_num);
                    }
                });
            },100);
        });
    }
}







/***
 * 清空该分类下所有文档
 */
function qingkong_doc() {
    var treeObj = $.fn.zTree.getZTreeObj("index_lm_tree");
    var nodes = treeObj.getSelectedNodes();
    var selectcateid =  nodes[0].cateid;

    var r=confirm("您确定清空该分类下所有的文档吗？");
    if (r==true){
        $.get(qingkong_doclink,{selectcateid:selectcateid},function (msg) {
            if(msg.code=='1'){
                $.alert("清空完毕，共删除【"+msg.data+"】记录");
                var treeObj = $.fn.zTree.getZTreeObj("index_lm_tree");
                var nodes = treeObj.getSelectedNodes();
                var selectcateid =  nodes[0].cateid;
                getdoclistbylmid(selectcateid,1);

            }
        });
    }


}

/***
 * 批量添加文档弹出框
 */
function import_doc_modal() {
    $("#i_w_importdoc_dialog").modal("show");
    setTimeout(function () {
        $("#i_w_importdoc_picker").html("选择附件");
        loadimportdocuploader();
    },500);
}

/***
 * 批量导入文档
 */
function i_w_importdoc_import() {
    var treeObj = $.fn.zTree.getZTreeObj("index_lm_tree");
    var nodes = treeObj.getSelectedNodes();
    var selectcateid =  nodes[0].cateid;
    var att_name_list = "";
    $("input[name='att_name']").each(function (_index,_this) {
        att_name_list+=","+_this.value;
    });
    if(att_name_list==""){
        return false;
    }
    $("#init_loading").modal("show");

    $.post(i_w_importdoc_importlink,{
        selectcateid:selectcateid,
        att_name_list:att_name_list
    },function (content) {
        $("#init_loading").modal("hide");

        if(content.code=="1"){
            $("#i_w_importdoc_dialog").modal('hide');
            $.alert({content:content.msg});
            getdoclistbylmid(selectcateid,1);
            return false;
        }
    });

}

/***
 * 加载上传组件
 */
function loadimportdocuploader() {
    $("#i_w_importdoc_uploadlist").html("");
    $("#i_w_importdoc_list").html("");

    var uploader = WebUploader.create({
        swf: './webuploader-0.1.5/Uploader.swf',
        auto:true,
        server: upload_file,
        pick: '#i_w_importdoc_picker',
        resize: false,
        fileNumLimit:1,
        formData:{
            filetype:10
        },
        accept:{
            title: '文本内容',
            extensions: 'xlsx',
            mimeTypes: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        },
        fileSizeLimit:10485760000
    });
    uploader.on( 'fileQueued', function( file ) {

        $("#i_w_importdoc_uploadlist").html( '<div id="' + file.id + '" class="item">' +
            '<h4 class="info">' + file.name + '</h4>' +
            '<p class="state">等待上传...</p>' +
            '</div>' );
    });
    uploader.on( 'beforeFileQueued', function( file ) {
        uploader.reset();
    });

    uploader.on( 'uploadProgress', function( file, percentage ) {
        var $li = $( '#'+file.id ),
            $percent = $li.find('.progress .progress-bar');

        if ( !$percent.length ) {
            $percent = $('<div class="progress progress-striped active">' +
                '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                '</div>' +
                '</div>').appendTo( $li ).find('.progress-bar');
        }

        $li.find('p.state').text('上传中并正在处理，请稍等！！！');
        $percent.css( 'width', percentage * 100 + '%' );
    });
    //上传成功
    uploader.on( 'uploadSuccess', function( file,response ) {
        $( '#'+file.id ).find('p.state').text('上传完毕');

        setTimeout(function(){
            if(response.code=='1'){
                var htmlstr = "<tr id=\"att"+response.data.attachedid+"\" >"+
                    "<td>"+response.data.truename+"<input name='att_name' value='"+response.data.attachedid+"' style='display: none;' /></td>"+
                    "<td>"+response.data.size+"</td>"+
                    "<td><span class=\"label label-danger\" style='cursor: pointer;'  onclick=\"delAttached('"+response.data.attachedid+"')\">删除</span></td>"+
                    "</tr>";

                $("#i_w_importdoc_list").append(htmlstr);
            }
            $("#i_w_importdoc_uploadlist").html("");
            uploader.reset();
        },1000);

    });
    uploader.on( 'uploadError', function( file ) {
        $( '#'+file.id ).find('p.state').text('上传出错');
        uploader.reset();
    });
    uploader.on( 'uploadComplete', function( file ) {
        $( '#'+file.id ).find('.progress').fadeOut();
    });
}

/***
 *  删除附件
 */
function delAttached(attachedid) {
    $.confirm({
        title:"提示",
        content:"您确认删除此附件吗？",
        buttons:{
            "确定":function () {
                $.get(delAttached_link,{attachedid:attachedid},function (msg) {
                    if (msg.code=='1'){
                        $("#att"+attachedid).remove();
                        $.confirm({
                            title: '提示',
                            content: '成功删除附件！',
                            autoClose: '确定|2000',
                            buttons: {
                                确定: {
                                }
                            }
                        });
                    }
                });
            },
            "取消":function () {

            }
        }
    });
}




/****
 * 修改文档
 * @param _docid
 */
function updateDoc(_docid) {
    var treeObj = $.fn.zTree.getZTreeObj("index_lm_tree");
    var nodes = treeObj.getSelectedNodes();
    sessionStorage.setItem("selectlmid",nodes[0].cateid);
    sessionStorage.setItem("updatedocid",_docid);
    window.open(adddocframe_link);
}

/***
 * 文档发布
 */
function publicDoc(_docid) {
    var treeObj = $.fn.zTree.getZTreeObj("index_lm_tree");
    var nodes = treeObj.getSelectedNodes();
    var cateid = nodes[0].cateid;
    $.get(publicDoclink,{
        docid:_docid
    },function (_info) {
        $.alert(_info.msg);
        getdoclistbylmid(cateid,doc_pages);
    });
}
/***
 * 添加文档
 */
function index_lm_adddoc() {

    var treeObj = $.fn.zTree.getZTreeObj("index_lm_tree");
    var nodes = treeObj.getSelectedNodes();
    var selectlmid = nodes[0].cateid;
    sessionStorage.setItem("selectlmid",selectlmid);
    sessionStorage.setItem("updatedocid",-1);
    window.open(adddocframe_link);
}


/***
 * 获取申请单分类数据
 */
function findlmdata_link_fun(_node) {
    var usertoken = sessionStorage.getItem("usertoken");
    $.get(findlmdata_link,{
        node:_node,
        usertoken:usertoken
    },function (data) {
        if (data.code=='1'){
            initTree(data.data);
        }
    });
}

/***
 * 初始化树结构
 */
function initTree(_treedata) {
    var zTreeObj;
    // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
    var setting = {
        data:{
            keep:{
                parent:true
            }
        },
        callback:{
            onRightClick:function (event, treeId, treeNode) {
                zTreeObj.selectNode(treeNode);
                var clientx = event.clientX-210;
                var clienty = event.clientY-50;

                $("#index_lm_youjian_cateid").html(treeNode.cateid);
                $("#index_lm_youjian").css({"margin-left":clientx,"margin-top":clienty,"display":"block"});

            },
            onExpand:function (event, treeId, treeNode) {

                var zAsync = treeNode.zAsync;
                //展开
                var treenodeid = treeNode.cateid;
                var usertoken = sessionStorage.getItem("usertoken");
                $.get(findlmdata_link,{
                    node:treenodeid,
                    usertoken:usertoken
                },function (data) {
                    if (data.code=='1'){
                        var sonnode = data.data.datalist;

                        zTreeObj.addNodes(treeNode, sonnode);
                    }
                });
            },
            onCollapse:function (event, treeId, treeNode) {
                //折叠后
                var treenodeid = treeNode.cateid;
                zTreeObj.removeChildNodes(treeNode);  

            },
            onClick:function (event, treeId, treeNode,clickFlag) {
                //点击选择
                getdoclistbylmid(treeNode.cateid,1);
                index_lm_tab(1);
                //栏目文档操作权限验证
                boollmdocauth(treeNode.cateid);



            }
        }
    };
    // zTree 的数据属性，深入使用请参考 API 文档（zTreeNode 节点数据详解）
    zTreeObj = $.fn.zTree.init($("#index_lm_tree"), setting, _treedata.datalist);
    var nodes = zTreeObj.getNodes();
    zTreeObj.selectNode(nodes[0]);
    getdoclistbylmid(0,1);
    index_lm_tab(1);
    boollmdocauth(0);
}

/***
 * 登录用户栏目文档操作权限控制
 * @param _lmid
 */
function boollmdocauth(_lmid) {
    var usertoken = sessionStorage.getItem("usertoken");

    $(".doc_auth_add").prop("disabled",false);
    $(".doc_auth_update").prop("disabled",false);
    $(".doc_auth_delete").prop("disabled",false);

    $.get(boollmdocauthlink,{
        lmid:_lmid,
        usertoken:usertoken
    },function (_info) {
        if (_info.code=="1"){
            var treeObj = $.fn.zTree.getZTreeObj("index_lm_tree");
            var nodes = treeObj.getSelectedNodes();
            var cateid = nodes[0].cateid;

            var datalist = _info.data;
            for(var i in datalist){
                var dataobj = datalist[i];
                var lmid = dataobj.lmid;
                var optype = dataobj.optype;
                if(cateid==lmid){
                    if(optype=="10"){
                        $(".doc_auth_add").prop("disabled",true);
                    }else if (optype=="20"){
                        $(".doc_auth_update").prop("disabled",true);
                    }else if (optype=="30"){
                        $(".doc_auth_delete").prop("disabled",true);
                    }
                }
            }
        }else {
            $(".doc_auth_add").prop("disabled",true);
            $(".doc_auth_update").prop("disabled",true);
            $(".doc_auth_delete").prop("disabled",true);
        }
    });
}


function getdoclistbylmid(lmid,_pagenum) {
    $.ajax({
        type:"post",
        url:getdoclistbylmidlink,
        data:{
            lmid:lmid,
            pagenum:_pagenum
        },
        cache:false,
        async:false,
        success:function (content) {
            if (content.code=='1'){
                var dataobj = content.data;
                var htmlstr = "";
                for (var i in dataobj){
                    var doctypetext = "";
                    var doctype = dataobj[i].doctype;
                    if(doctype=="10"){
                        doctypetext = "未发布";
                    }else if(doctype=="50"){
                        doctypetext = "已发布";
                    }


                    htmlstr+="<tr>" +
                                    "<td><a href='javascript:void(0);' onclick='openDoc(\""+dataobj[i].docid+"\")'>"+dataobj[i].docname+"</a></td>" +
                                    "<td>"+dataobj[i].crdate+"</td>" +
                                    "<td>"+doctypetext+"</td>" +
                                    "<td>" +
                                        "<button type=\"button\" class=\"btn btn-danger doc_auth_delete\" onclick='deleteDoc(\""+dataobj[i].docid+"\")'>删除文档</button>" +
                                        "<button type=\"button\" style='margin-left: 20px;' class=\"btn btn-info doc_auth_update\" onclick='updateDoc(\""+dataobj[i].docid+"\")'>修改文档</button>" +
                                        "<button type=\"button\" style='margin-left: 20px;' class=\"btn btn-info\" onclick='publicDoc(\""+dataobj[i].docid+"\")'>发布文档</button>" +
                                    "</td>" +
                               "</tr>";

                }
                $("#index_lm_doc_content").html(htmlstr);

                getdoclistbylmidpage(_pagenum,content.pages);
            }else {
                $("#index_lm_doc_content").html(content.msg);
            }

        },
        error:function (content) {
            alert(content);
        }


    });
}
//数据分页
function getdoclistbylmidpage(_pagenum,_pages){
    //处理分页
    $('#index_lm_cont_1_page').bootstrapPaginator({
        currentPage: _pagenum,
        totalPages: _pages,
        size:"normal",
        bootstrapMajorVersion: 3,
        alignment:"right",
        numberOfPages:5,
        itemTexts: function (type, page, current) {
            switch (type) {
                case "first":
                    return "首页";
                case "prev":
                    return "上一页";
                case "next":
                    return "下一页";
                case "last":
                    return "末页";
                case "page":
                    return page;
            }
        },
        onPageClicked: function (event, originalEvent, type, page) {
            var treeObj = $.fn.zTree.getZTreeObj("index_lm_tree");
            var nodes = treeObj.getSelectedNodes();
            var selectlmid = nodes[0].cateid;
            doc_pages = page;
            getdoclistbylmid(selectlmid,page);
        }
    });
}
/***
 * 删除文档
 * @param _docid
 */
function deleteDoc(_docid) {
    var r=confirm("您确定删除此文档吗？");
    if (r==true){
        $.get(deletedocbydocid,{docid:_docid},function (msg) {
            if(msg.code=='1'){
                alert("删除成功");
                var treeObj = $.fn.zTree.getZTreeObj("index_lm_tree");
                var nodes = treeObj.getSelectedNodes();
                var selectcateid =  nodes[0].cateid;
                getdoclistbylmid(selectcateid,1);

            }
        });
    }
}

/***
 * 打开文档
 * @param _docid
 */
function openDoc(_docid) {
    sessionStorage.setItem("docid",_docid);
    window.open(docview_link);
}

/***
 * 添加节点弹出窗口
 */
function index_lm_youjian_addnode() {
    index_lm_youjian_unb();
    $("#model_lm_nodename").val("");
    $("#model_lm_nodedesc").val("");
    $("#model_lm").modal('show');
}

/***
 * 栏目删除节点
 */
function index_lm_youjian_deletenode() {
    var treeObj = $.fn.zTree.getZTreeObj("index_lm_tree");
    var nodes = treeObj.getSelectedNodes();
    var r=confirm("您确定删除此栏目吗？");
    if (r==true){
        $.get(deletelmbylmid,{lmid:nodes[0].cateid},function (msg) {
            if(msg.code=='1'){
                alert("删除成功");
                treeObj.removeNode(nodes[0]);
            }
        });
    }

}


/***
 * 提交更改
 */
function model_lm_model_submit() {
    var model_lm_nodename = $.trim($("#model_lm_nodename").val());
    var model_lm_nodedesc = $.trim($("#model_lm_nodedesc").val());
    var model_lm_nodetype = $.trim($("#model_lm_nodetype").val());
    var treeObj = $.fn.zTree.getZTreeObj("index_lm_tree");
    var nodes = treeObj.getSelectedNodes();
    $.post(insertlm_link,{
        node_name:model_lm_nodename,
        node_desc:model_lm_nodedesc,
        selectlmid:nodes[0].cateid,
        model_lm_nodetype:model_lm_nodetype
    },function (data) {
        if (data.code=="1"){
            $("#model_lm").modal('hide');
            var usertoken = sessionStorage.getItem("usertoken");
            $.get(findlmdata_link,{
                node:data.data,
                usertoken:usertoken
            },function (data) {
                if (data.code=='1'){
                    var selecttreeobj = $.fn.zTree.getZTreeObj("index_lm_tree");
                    var nodes = selecttreeobj.getSelectedNodes();
                    selecttreeobj.removeChildNodes(nodes[0]);
                    selecttreeobj.addNodes(nodes[0], data.data.datalist);
                }
            });

        }
    });
}


/***
 * 取消右键菜单
 */
function index_lm_youjian_unb() {
    $("#index_lm_youjian").css("display","none");
}
function index_lm_youjian_over() {
    $("#index_lm_youjian").css("display","block");
}